home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / u_man / cat1 / perlref.Z / perlref
Encoding:
Text File  |  1998-10-28  |  33.0 KB  |  925 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       perlref - Perl references and    nested data structures
  10.  
  11.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.       Before release 5 of Perl it was difficult to represent
  13.       complex data structures, because all references had to be
  14.       symbolic--and    even then it was difficult to refer to a
  15.       variable instead of a    symbol table entry.  Perl now not only
  16.       makes    it easier to use symbolic references to    variables, but
  17.       also lets you    have "hard" references to any piece of data or
  18.       code.     Any scalar may    hold a hard reference.    Because    arrays
  19.       and hashes contain scalars, you can now easily build arrays
  20.       of arrays, arrays of hashes, hashes of arrays, arrays    of
  21.       hashes of functions, and so on.
  22.  
  23.       Hard references are smart--they keep track of    reference
  24.       counts for you, automatically    freeing    the thing referred to
  25.       when its reference count goes    to zero.  (Note: the reference
  26.       counts for values in self-referential    or cyclic data
  27.       structures may not go    to zero    without    a little help; see the
  28.       section on _T_w_o-_P_h_a_s_e_d    _G_a_r_b_a_g_e    _C_o_l_l_e_c_t_i_o_n in the _p_e_r_l_o_b_j
  29.       manpage for a    detailed explanation.)    If that    thing happens
  30.       to be    an object, the object is destructed.  See the _p_e_r_l_o_b_j
  31.       manpage for more about objects.  (In a sense,    everything in
  32.       Perl is an object, but we usually reserve the    word for
  33.       references to    objects    that have been officially "blessed"
  34.       into a class package.)
  35.  
  36.       Symbolic references are names    of variables or    other objects,
  37.       just as a symbolic link in a Unix filesystem contains    merely
  38.       the name of a    file.  The *glob notation is a kind of
  39.       symbolic reference.  (Symbolic references are    sometimes
  40.       called "soft references", but    please don't call them that;
  41.       references are confusing enough without useless synonyms.)
  42.  
  43.       In contrast, hard references are more    like hard links    in a
  44.       Unix file system: They are used to access an underlying
  45.       object without concern for what its (other) name is.    When
  46.       the word "reference" is used without an adjective, as    in the
  47.       following paragraph, it is usually talking about a hard
  48.       reference.
  49.  
  50.       References are easy to use in    Perl.  There is    just one
  51.       overriding principle:    Perl does no implicit referencing or
  52.       dereferencing.  When a scalar    is holding a reference,    it
  53.       always behaves as a simple scalar.  It doesn't magically
  54.       start    being an array or hash or subroutine; you have to tell
  55.       it explicitly    to do so, by dereferencing it.
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  71.  
  72.  
  73.  
  74.       MMMMaaaakkkkiiiinnnngggg RRRReeeeffffeeeerrrreeeennnncccceeeessss
  75.  
  76.       References can be created in several ways.
  77.  
  78.       1.  By using the backslash operator on a variable,
  79.           subroutine, or value.  (This works much like the &
  80.           (address-of) operator in C.)  Note that this typically
  81.           creates _A_N_O_T_H_E_R reference    to a variable, because there's
  82.           already a    reference to the variable in the symbol    table.
  83.           But the symbol table reference might go away, and    you'll
  84.           still have the reference that the    backslash returned.
  85.           Here are some examples:
  86.  
  87.           $scalarref = \$foo;
  88.           $arrayref  = \@ARGV;
  89.           $hashref   = \%ENV;
  90.           $coderef   = \&handler;
  91.           $globref   = \*foo;
  92.  
  93.           It isn't possible    to create a true reference to an IO
  94.           handle (filehandle or dirhandle) using the backslash
  95.           operator.     The most you can get is a reference to    a
  96.           typeglob,    which is actually a complete symbol table
  97.           entry.  But see the explanation of the *foo{THING}
  98.           syntax below.  However, you can still use    type globs and
  99.           globrefs as though they were IO handles.
  100.  
  101.       2.  A    reference to an    anonymous array    can be created using
  102.           square brackets:
  103.  
  104.           $arrayref = [1, 2, ['a', 'b',    'c']];
  105.  
  106.           Here we've created a reference to    an anonymous array of
  107.           three elements whose final element is itself a reference
  108.           to another anonymous array of three elements.  (The
  109.           multidimensional syntax described    later can be used to
  110.           access this.  For    example, after the above, $arrayref-
  111.           >[2][1] would have the value "b".)
  112.  
  113.           Note that    taking a reference to an enumerated list is
  114.           not the same as using square brackets--instead it's the
  115.           same as creating a list of references!
  116.  
  117.           @list    = (\$a,    \@b, \%c);
  118.           @list    = \($a,    @b, %c);      #    same thing!
  119.  
  120.           As a special case, \(@foo) returns a list    of references
  121.           to the contents of @foo, not a reference to @foo itself.
  122.           Likewise for %foo.
  123.  
  124.       3.  A    reference to an    anonymous hash can be created using
  125.           curly brackets:
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  137.  
  138.  
  139.  
  140.           $hashref = {
  141.               'Adam'  => 'Eve',
  142.               'Clyde' => 'Bonnie',
  143.           };
  144.  
  145.           Anonymous    hash and array composers like these can    be
  146.           intermixed freely    to produce as complicated a structure
  147.           as you want.  The    multidimensional syntax    described
  148.           below works for these too.  The values above are
  149.           literals,    but variables and expressions would work just
  150.           as well, because assignment operators in Perl (even
  151.           within _l_o_c_a_l() or    _m_y()) are executable statements, not
  152.           compile-time declarations.
  153.  
  154.           Because curly brackets (braces) are used for several
  155.           other things including BLOCKs, you may occasionally have
  156.           to disambiguate braces at    the beginning of a statement
  157.           by putting a + or    a return in front so that Perl
  158.           realizes the opening brace isn't starting    a BLOCK.  The
  159.           economy and mnemonic value of using curlies is deemed
  160.           worth this occasional extra hassle.
  161.  
  162.           For example, if you wanted a function to make a new hash
  163.           and return a reference to    it, you    have these options:
  164.  
  165.           sub hashem {          {    @_ } }     # silently wrong
  166.           sub hashem {         +{    @_ } }     # ok
  167.           sub hashem { return {    @_ } }     # ok
  168.  
  169.           On the other hand, if you    want the other meaning,    you
  170.           can do this:
  171.  
  172.           sub showem {          {    @_ } }     # ambiguous (currently    ok, but    may change)
  173.           sub showem {         {;    @_ } }     # ok
  174.           sub showem { { return    @_ } }     # ok
  175.  
  176.           Note how the leading +{ and {; always serve to
  177.           disambiguate the expression to mean either the HASH
  178.           reference, or the    BLOCK.
  179.  
  180.       4.  A    reference to an    anonymous subroutine can be created by
  181.           using sub    without    a subname:
  182.  
  183.           $coderef = sub { print "Boink!\n" };
  184.  
  185.           Note the presence    of the semicolon.  Except for the fact
  186.           that the code inside isn't executed immediately, a sub
  187.           {} is not    so much    a declaration as it is an operator,
  188.           like do{}    or eval{}.  (However, no matter    how many times
  189.           you execute that particular line (unless you're in an
  190.           eval("...")), $coderef will still    have a reference to
  191.           the _S_A_M_E anonymous subroutine.)
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  203.  
  204.  
  205.  
  206.           Anonymous    subroutines act    as closures with respect to
  207.           _m_y() variables, that is, variables visible lexically
  208.           within the current scope.     Closure is a notion out of
  209.           the Lisp world that says if you define an    anonymous
  210.           function in a particular lexical context,    it pretends to
  211.           run in that context even when it's called    outside    of the
  212.           context.
  213.  
  214.           In human terms, it's a funny way of passing arguments to
  215.           a    subroutine when    you define it as well as when you call
  216.           it.  It's    useful for setting up little bits of code to
  217.           run later, such as callbacks.  You can even do object-
  218.           oriented stuff with it, though Perl already provides a
  219.           different    mechanism to do    that--see the _p_e_r_l_o_b_j manpage.
  220.  
  221.           You can also think of closure as a way to    write a
  222.           subroutine template without using    eval.  (In fact, in
  223.           version 5.000, eval was the _o_n_l_y way to get closures.
  224.           You may wish to use "require 5.001" if you use
  225.           closures.)
  226.  
  227.           Here's a small example of    how closures works:
  228.  
  229.           sub newprint {
  230.               my $x = shift;
  231.               return sub { my $y = shift; print    "$x, $y!\n"; };
  232.           }
  233.           $h = newprint("Howdy");
  234.           $g = newprint("Greetings");
  235.  
  236.           # Time passes...
  237.  
  238.           &$h("world");
  239.           &$g("earthlings");
  240.  
  241.           This prints
  242.  
  243.           Howdy, world!
  244.           Greetings, earthlings!
  245.  
  246.           Note particularly    that $x    continues to refer to the
  247.           value passed into    _n_e_w_p_r_i_n_t() _d_e_s_p_i_t_e the fact that the
  248.           "my $x" has seemingly gone out of    scope by the time the
  249.           anonymous    subroutine runs.  That's what closure is all
  250.           about.
  251.  
  252.           This applies only    to lexical variables, by the way.
  253.           Dynamic variables    continue to work as they have always
  254.           worked.  Closure is not something    that most Perl
  255.           programmers need trouble themselves about    to begin with.
  256.  
  257.  
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  269.  
  270.  
  271.  
  272.       5.  References are often returned by special subroutines
  273.           called constructors.  Perl objects are just references
  274.           to a special kind    of object that happens to know which
  275.           package it's associated with.  Constructors are just
  276.           special subroutines that know how    to create that
  277.           association.  They do so by starting with    an ordinary
  278.           reference, and it    remains    an ordinary reference even
  279.           while it's also being an object.    Constructors are often
  280.           named _n_e_w() and called indirectly:
  281.  
  282.           $objref = new    Doggie (Tail =>    'short', Ears => 'long');
  283.  
  284.           But don't    have to    be:
  285.  
  286.           $objref   = Doggie->new(Tail => 'short', Ears    => 'long');
  287.  
  288.           use Term::Cap;
  289.           $terminal = Term::Cap->Tgetent( { OSPEED => 9600 });
  290.  
  291.           use Tk;
  292.           $main       = MainWindow->new();
  293.           $menubar = $main->Frame(-relief           => "raised",
  294.                       -borderwidth           => 2)
  295.  
  296.  
  297.       6.  References of the    appropriate type can spring into
  298.           existence    if you dereference them    in a context that
  299.           assumes they exist.  Because we haven't talked about
  300.           dereferencing yet, we can't show you any examples    yet.
  301.  
  302.       7.  A    reference can be created by using a special syntax,
  303.           lovingly known as    the *foo{THING}    syntax.     *foo{THING}
  304.           returns a    reference to the THING slot in *foo (which is
  305.           the symbol table entry which holds everything known as
  306.           foo).
  307.  
  308.           $scalarref = *foo{SCALAR};
  309.           $arrayref  = *ARGV{ARRAY};
  310.           $hashref   = *ENV{HASH};
  311.           $coderef   = *handler{CODE};
  312.           $ioref     = *STDIN{IO};
  313.           $globref   = *foo{GLOB};
  314.  
  315.           All of these are self-explanatory    except for *foo{IO}.
  316.           It returns the IO    handle,    used for file handles (the
  317.           open entry in the    _p_e_r_l_f_u_n_c manpage), sockets (the    socket
  318.           entry in the _p_e_r_l_f_u_n_c manpage and    the socketpair entry
  319.           in the _p_e_r_l_f_u_n_c manpage),    and directory handles (the
  320.           opendir entry in the _p_e_r_l_f_u_n_c manpage).  For
  321.           compatibility with previous versions of Perl,
  322.           *foo{FILEHANDLE} is a synonym for    *foo{IO}.
  323.  
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  335.  
  336.  
  337.  
  338.           *foo{THING} returns undef    if that    particular THING
  339.           hasn't been used yet, except in the case of scalars.
  340.           *foo{SCALAR} returns a reference to an anonymous scalar
  341.           if $foo hasn't been used yet.  This might    change in a
  342.           future release.
  343.  
  344.           *foo{IO} is an alternative to the    \*HANDLE mechanism
  345.           given in the section on _T_y_p_e_g_l_o_b_s    _a_n_d _F_i_l_e_h_a_n_d_l_e_s    in the
  346.           _p_e_r_l_d_a_t_a manpage for passing filehandles into or out of
  347.           subroutines, or storing into larger data structures.
  348.           Its disadvantage is that it won't    create a new
  349.           filehandle for you.  Its advantage is that you have no
  350.           risk of clobbering more than you want to with a typeglob
  351.           assignment, although if you assign to a scalar instead
  352.           of a typeglob, you're ok.
  353.  
  354.           splutter(*STDOUT);
  355.           splutter(*STDOUT{IO});
  356.  
  357.           sub splutter {
  358.               my $fh = shift;
  359.               print $fh    "her um    well a hmmm\n";
  360.           }
  361.  
  362.           $rec = get_rec(*STDIN);
  363.           $rec = get_rec(*STDIN{IO});
  364.  
  365.           sub get_rec {
  366.               my $fh = shift;
  367.               return scalar <$fh>;
  368.           }
  369.  
  370.  
  371.       UUUUssssiiiinnnngggg    RRRReeeeffffeeeerrrreeeennnncccceeeessss
  372.  
  373.       That's it for    creating references.  By now you're probably
  374.       dying    to know    how to use references to get back to your
  375.       long-lost data.  There are several basic methods.
  376.  
  377.       1.  Anywhere you'd put an identifier (or chain of
  378.           identifiers) as part of a    variable or subroutine name,
  379.           you can replace the identifier with a simple scalar
  380.           variable containing a reference of the correct type:
  381.  
  382.           $bar = $$scalarref;
  383.           push(@$arrayref, $filename);
  384.           $$arrayref[0]    = "January";
  385.           $$hashref{"KEY"} = "VALUE";
  386.           &$coderef(1,2,3);
  387.           print    $globref "output\n";
  388.  
  389.           It's important to    understand that    we are specifically
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  401.  
  402.  
  403.  
  404.           _N_O_T dereferencing    $arrayref[0] or    $hashref{"KEY"}    there.
  405.           The dereference of the scalar variable happens _B_E_F_O_R_E it
  406.           does any key lookups.  Anything more complicated than a
  407.           simple scalar variable must use methods 2    or 3 below.
  408.           However, a "simple scalar" includes an identifier    that
  409.           itself uses method 1 recursively.     Therefore, the
  410.           following    prints "howdy".
  411.  
  412.           $refrefref = \\\"howdy";
  413.           print    $$$$refrefref;
  414.  
  415.  
  416.       2.  Anywhere you'd put an identifier (or chain of
  417.           identifiers) as part of a    variable or subroutine name,
  418.           you can replace the identifier with a BLOCK returning a
  419.           reference    of the correct type.  In other words, the
  420.           previous examples    could be written like this:
  421.  
  422.           $bar = ${$scalarref};
  423.           push(@{$arrayref}, $filename);
  424.           ${$arrayref}[0] = "January";
  425.           ${$hashref}{"KEY"} = "VALUE";
  426.           &{$coderef}(1,2,3);
  427.           $globref->print("output\n");    # iff IO::Handle is loaded
  428.  
  429.           Admittedly, it's a little    silly to use the curlies in
  430.           this case, but the BLOCK can contain any arbitrary
  431.           expression, in particular, subscripted expressions:
  432.  
  433.           &{ $dispatch{$index} }(1,2,3);      #    call correct routine
  434.  
  435.           Because of being able to omit the    curlies    for the    simple
  436.           case of $$x, people often    make the mistake of viewing
  437.           the dereferencing    symbols    as proper operators, and
  438.           wonder about their precedence.  If they were, though,
  439.           you could    use parentheses    instead    of braces.  That's not
  440.           the case.     Consider the difference below;    case 0 is a
  441.           short-hand version of case 1, _N_O_T    case 2:
  442.  
  443.           $$hashref{"KEY"}   = "VALUE";          #    CASE 0
  444.           ${$hashref}{"KEY"} = "VALUE";          #    CASE 1
  445.           ${$hashref{"KEY"}} = "VALUE";          #    CASE 2
  446.           ${$hashref->{"KEY"}} = "VALUE";     #    CASE 3
  447.  
  448.           Case 2 is    also deceptive in that you're accessing    a
  449.           variable called %hashref,    not dereferencing through
  450.           $hashref to the hash it's    presumably referencing.     That
  451.           would be case 3.
  452.  
  453.       3.  Subroutine calls and lookups of individual array
  454.           elements arise often enough that it gets cumbersome to
  455.           use method 2.  As    a form of syntactic sugar, the
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  467.  
  468.  
  469.  
  470.           examples for method 2 may    be written:
  471.  
  472.           $arrayref->[0] = "January";    # Array    element
  473.           $hashref->{"KEY"} = "VALUE";    # Hash element
  474.           $coderef->(1,2,3);        # Subroutine call
  475.  
  476.           The left side of the arrow can be    any expression
  477.           returning    a reference, including a previous dereference.
  478.           Note that    $array[$x] is _N_O_T the same thing as $array-
  479.           >[$x] here:
  480.  
  481.           $array[$x]->{"foo"}->[0] = "January";
  482.  
  483.           This is one of the cases we mentioned earlier in which
  484.           references could spring into existence when in an    lvalue
  485.           context.    Before this statement, $array[$x] may have
  486.           been undefined.  If so, it's automatically defined with
  487.           a    hash reference so that we can look up {"foo"} in it.
  488.           Likewise $array[$x]->{"foo"} will    automatically get
  489.           defined with an array reference so that we can look up
  490.           [0] in it.  This process is called _a_u_t_o_v_i_v_i_f_i_c_a_t_i_o_n.
  491.  
  492.           One more thing here.  The    arrow is optional _B_E_T_W_E_E_N
  493.           brackets subscripts, so you can shrink the above down to
  494.  
  495.           $array[$x]{"foo"}[0] = "January";
  496.  
  497.           Which, in    the degenerate case of using only ordinary
  498.           arrays, gives you    multidimensional arrays    just like C's:
  499.  
  500.           $score[$x][$y][$z] +=    42;
  501.  
  502.           Well, okay, not entirely like C's    arrays,    actually.  C
  503.           doesn't know how to grow its arrays on demand.  Perl
  504.           does.
  505.  
  506.       4.  If a reference happens to    be a reference to an object,
  507.           then there are probably methods to access    the things
  508.           referred to, and you should probably stick to those
  509.           methods unless you're in the class package that defines
  510.           the object's methods.  In    other words, be    nice, and
  511.           don't violate the    object's encapsulation without a very
  512.           good reason.  Perl does not enforce encapsulation.  We
  513.           are not totalitarians here.  We do expect    some basic
  514.           civility though.
  515.  
  516.       The _r_e_f() operator may be used to determine what type    of
  517.       thing    the reference is pointing to.  See the _p_e_r_l_f_u_n_c
  518.       manpage.
  519.  
  520.       The _b_l_e_s_s() operator may be used to associate    the object a
  521.       reference points to with a package functioning as an object
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  533.  
  534.  
  535.  
  536.       class.  See the _p_e_r_l_o_b_j manpage.
  537.  
  538.       A typeglob may be dereferenced the same way a    reference can,
  539.       because the dereference syntax always    indicates the kind of
  540.       reference desired.  So ${*foo} and ${\$foo} both indicate
  541.       the same scalar variable.
  542.  
  543.       Here's a trick for interpolating a subroutine    call into a
  544.       string:
  545.  
  546.           print "My    sub returned @{[mysub(1,2,3)]} that time.\n";
  547.  
  548.       The way it works is that when    the @{...} is seen in the
  549.       double-quoted    string,    it's evaluated as a block.  The    block
  550.       creates a reference to an anonymous array containing the
  551.       results of the call to mysub(1,2,3).    So the whole block
  552.       returns a reference to an array, which is then dereferenced
  553.       by @{...} and    stuck into the double-quoted string. This
  554.       chicanery is also useful for arbitrary expressions:
  555.  
  556.           print "That yields @{[$n + 5]} widgets\n";
  557.  
  558.  
  559.       SSSSyyyymmmmbbbboooolllliiiicccc rrrreeeeffffeeeerrrreeeennnncccceeeessss
  560.  
  561.       We said that references spring into existence    as necessary
  562.       if they are undefined, but we    didn't say what    happens    if a
  563.       value    used as    a reference is already defined,    but _I_S_N'_T a
  564.       hard reference.  If you use it as a reference    in this    case,
  565.       it'll    be treated as a    symbolic reference.  That is, the
  566.       value    of the scalar is taken to be the _N_A_M_E of a variable,
  567.       rather than a    direct link to a (possibly) anonymous value.
  568.  
  569.       People frequently expect it to work like this.  So it    does.
  570.  
  571.           $name = "foo";
  572.           $$name = 1;          # Sets $foo
  573.           ${$name} = 2;          # Sets $foo
  574.           ${$name x    2} = 3;          # Sets $foofoo
  575.           $name->[0] = 4;          # Sets $foo[0]
  576.           @$name = ();          # Clears @foo
  577.           &$name();              # Calls &foo() (as in    Perl 4)
  578.           $pack = "THAT";
  579.           ${"${pack}::$name"} = 5;      # Sets $THAT::foo without eval
  580.  
  581.       This is very powerful, and slightly dangerous, in that it's
  582.       possible to intend (with the utmost sincerity) to use    a hard
  583.       reference, and accidentally use a symbolic reference
  584.       instead.  To protect against that, you can say
  585.  
  586.           use strict 'refs';
  587.  
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  599.  
  600.  
  601.  
  602.       and then only    hard references    will be    allowed    for the    rest
  603.       of the enclosing block.  An inner block may countermand that
  604.       with
  605.  
  606.           no strict    'refs';
  607.  
  608.       Only package variables (globals, even    if localized) are
  609.       visible to symbolic references.  Lexical variables (declared
  610.       with _m_y()) aren't in a symbol    table, and thus    are invisible
  611.       to this mechanism.  For example:
  612.  
  613.           local $value = 10;
  614.           $ref = \$value;
  615.           {
  616.           my $value = 20;
  617.           print    $$ref;
  618.           }
  619.  
  620.       This will still print    10, not    20.  Remember that _l_o_c_a_l()
  621.       affects package variables, which are all "global" to the
  622.       package.
  623.  
  624.       NNNNooootttt----ssssoooo----ssssyyyymmmmbbbboooolllliiiicccc rrrreeeeffffeeeerrrreeeennnncccceeeessss
  625.  
  626.       A new    feature    contributing to    readability in perl version
  627.       5.001    is that    the brackets around a symbolic reference
  628.       behave more like quotes, just    as they    always have within a
  629.       string.  That    is,
  630.  
  631.           $push = "pop on ";
  632.           print "${push}over";
  633.  
  634.       has always meant to print "pop on over", despite the fact
  635.       that push is a reserved word.     This has been generalized to
  636.       work the same    outside    of quotes, so that
  637.  
  638.           print ${push} . "over";
  639.  
  640.       and even
  641.  
  642.           print ${ push } .    "over";
  643.  
  644.       will have the    same effect.  (This would have been a syntax
  645.       error    in Perl    5.000, though Perl 4 allowed it    in the
  646.       spaceless form.)  Note that this construct is    _n_o_t considered
  647.       to be    a symbolic reference when you're using strict refs:
  648.  
  649.           use strict 'refs';
  650.           ${ bareword };      # Okay, means    $bareword.
  651.           ${ "bareword" };      # Error, symbolic reference.
  652.  
  653.       Similarly, because of    all the    subscripting that is done
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  665.  
  666.  
  667.  
  668.       using    single words, we've applied the    same rule to any
  669.       bareword that    is used    for subscripting a hash.  So now,
  670.       instead of writing
  671.  
  672.           $array{ "aaa" }{ "bbb" }{    "ccc" }
  673.  
  674.       you can write    just
  675.  
  676.           $array{ aaa }{ bbb }{ ccc    }
  677.  
  678.       and not worry    about whether the subscripts are reserved
  679.       words.  In the rare event that you do    wish to    do something
  680.       like
  681.  
  682.           $array{ shift }
  683.  
  684.       you can force    interpretation as a reserved word by adding
  685.       anything that    makes it more than a bareword:
  686.  
  687.           $array{ shift() }
  688.           $array{ +shift }
  689.           $array{ shift @_ }
  690.  
  691.       The ----wwww switch    will warn you if it interprets a reserved word
  692.       as a string.    But it will no longer warn you about using
  693.       lowercase words, because the string is effectively quoted.
  694.  
  695.       PPPPsssseeeeuuuuddddoooo----hhhhaaaasssshhhheeeessss:::: UUUUssssiiiinnnngggg aaaannnn aaaarrrrrrrraaaayyyy    aaaassss aaaa hhhhaaaasssshhhh
  696.  
  697.       WARNING:  This section describes an experimental feature.
  698.       Details may change without notice in future versions.
  699.  
  700.       Beginning with release 5.005 of Perl you can use an array
  701.       reference in some contexts that would    normally require a
  702.       hash reference.  This    allows you to access array elements
  703.       using    symbolic names,    as if they were    fields in a structure.
  704.  
  705.       For this to work, the    array must contain extra information.
  706.       The first element of the array has to    be a hash reference
  707.       that maps field names    to array indices.  Here    is an example:
  708.  
  709.          $struct = [{foo =>    1, bar => 2}, "FOO", "BAR"];
  710.  
  711.          $struct->{foo};  #    same as    $struct->[1], i.e. "FOO"
  712.          $struct->{bar};  #    same as    $struct->[2], i.e. "BAR"
  713.  
  714.          keys %$struct;   #    will return ("foo", "bar") in some order
  715.          values %$struct; #    will return ("FOO", "BAR") in same some    order
  716.  
  717.          while (my($k,$v) =    each %$struct) {
  718.          print "$k => $v\n";
  719.          }
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  731.  
  732.  
  733.  
  734.       Perl will raise an exception if you try to delete keys from
  735.       a pseudo-hash    or try to access nonexistent fields.  For
  736.       better performance, Perl can also do the translation from
  737.       field    names to array indices at compile time for typed
  738.       object references.  See the _f_i_e_l_d_s manpage.
  739.  
  740.       FFFFuuuunnnnccccttttiiiioooonnnn TTTTeeeemmmmppppllllaaaatttteeeessss
  741.  
  742.       As explained above, a    closure    is an anonymous    function with
  743.       access to the    lexical    variables visible when that function
  744.       was compiled.     It retains access to those variables even
  745.       though it doesn't get    run until later, such as in a signal
  746.       handler or a Tk callback.
  747.  
  748.       Using    a closure as a function    template allows    us to generate
  749.       many functions that act similarly.  Suppopose    you wanted
  750.       functions named after    the colors that    generated HTML font
  751.       changes for the various colors:
  752.  
  753.           print "Be    ", red("careful"), "with that ", green("light");
  754.  
  755.       The _r_e_d() and    _g_r_e_e_n()    functions would    be very    similar.  To
  756.       create these,    we'll assign a closure to a typeglob of    the
  757.       name of the function we're trying to build.
  758.  
  759.           @colors =    qw(red blue green yellow orange    purple violet);
  760.           for my $name (@colors) {
  761.           no strict 'refs';      # allow symbol table manipulation
  762.           *$name = *{uc    $name} = sub { "<FONT COLOR='$name'>@_</FONT>" };
  763.           }
  764.  
  765.       Now all those    different functions appear to exist
  766.       independently.  You can call _r_e_d(), _R_E_D(), _b_l_u_e(), _B_L_U_E(),
  767.       _g_r_e_e_n(), etc.     This technique    saves on both compile time and
  768.       memory use, and is less error-prone as well, since syntax
  769.       checks happen    at compile time.  It's critical    that any
  770.       variables in the anonymous subroutine    be lexicals in order
  771.       to create a proper closure.  That's the reasons for the my
  772.       on the loop iteration    variable.
  773.  
  774.       This is one of the only places where giving a    prototype to a
  775.       closure makes    much sense.  If    you wanted to impose scalar
  776.       context on the arguments of these functions (probably    not a
  777.       wise idea for    this particular    example), you could have
  778.       written it this way instead:
  779.  
  780.           *$name = sub ($) { "<FONT    COLOR='$name'>$_[0]</FONT>" };
  781.  
  782.       However, since prototype checking happens at compile time,
  783.       the assignment above happens too late    to be of much use.
  784.       You could address this by putting the    whole loop of
  785.       assignments within a BEGIN block, forcing it to occur    during
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  797.  
  798.  
  799.  
  800.       compilation.
  801.  
  802.       Access to lexicals that change over type--like those in the
  803.       for loop above--only works with closures, not    general
  804.       subroutines.    In the general case, then, named subroutines
  805.       do not nest properly,    although anonymous ones    do.  If    you
  806.       are accustomed to using nested subroutines in    other
  807.       programming languages    with their own private variables,
  808.       you'll have to work at it a bit in Perl.  The    intuitive
  809.       coding of this kind of thing incurs mysterious warnings
  810.       about    ``will not stay    shared''.  For example,    this won't
  811.       work:
  812.  
  813.           sub outer    {
  814.           my $x    = $_[0]    + 35;
  815.           sub inner { return $x    * 19 }     # WRONG
  816.           return $x + inner();
  817.           }
  818.  
  819.       A work-around    is the following:
  820.  
  821.           sub outer    {
  822.           my $x    = $_[0]    + 35;
  823.           local    *inner = sub { return $x * 19 };
  824.           return $x + inner();
  825.           }
  826.  
  827.       Now _i_n_n_e_r() can only be called from within _o_u_t_e_r(), because
  828.       of the temporary assignments of the closure (anonymous
  829.       subroutine).    But when it does, it has normal    access to the
  830.       lexical variable $x from the scope of    _o_u_t_e_r().
  831.  
  832.       This has the interesting effect of creating a    function local
  833.       to another function, something not normally supported    in
  834.       Perl.
  835.  
  836.      WWWWAAAARRRRNNNNIIIINNNNGGGG
  837.       You may not (usefully) use a reference as the    key to a hash.
  838.       It will be converted into a string:
  839.  
  840.           $x{ \$a }    = $a;
  841.  
  842.       If you try to    dereference the    key, it    won't do a hard
  843.       dereference, and you won't accomplish    what you're
  844.       attempting.  You might want to do something more like
  845.  
  846.           $r = \@a;
  847.           $x{ $r } = $r;
  848.  
  849.       And then at least you    can use    the _v_a_l_u_e_s(), which will be
  850.       real refs, instead of    the _k_e_y_s(), which won't.
  851.  
  852.  
  853.  
  854.  
  855.      Page 13                        (printed 10/23/98)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  863.  
  864.  
  865.  
  866.       The standard Tie::RefHash module provides a convenient
  867.       workaround to    this.
  868.  
  869.      SSSSEEEEEEEE AAAALLLLSSSSOOOO
  870.       Besides the obvious documents, source    code can be
  871.       instructive.    Some rather pathological examples of the use
  872.       of references    can be found in    the _t/_o_p/_r_e_f._t regression test
  873.       in the Perl source directory.
  874.  
  875.       See also the _p_e_r_l_d_s_c manpage and the _p_e_r_l_l_o_l manpage for how
  876.       to use references to create complex data structures, and the
  877.       _p_e_r_l_t_o_o_t manpage, the    _p_e_r_l_o_b_j    manpage, and the _p_e_r_l_b_o_t
  878.       manpage for how to use them to create    objects.
  879.  
  880.  
  881.  
  882.  
  883.  
  884.  
  885.  
  886.  
  887.  
  888.  
  889.  
  890.  
  891.  
  892.  
  893.  
  894.  
  895.  
  896.  
  897.  
  898.  
  899.  
  900.  
  901.  
  902.  
  903.  
  904.  
  905.  
  906.  
  907.  
  908.  
  909.  
  910.  
  911.  
  912.  
  913.  
  914.  
  915.  
  916.  
  917.  
  918.  
  919.  
  920.  
  921.      Page 14                        (printed 10/23/98)
  922.  
  923.  
  924.  
  925.